<?php

namespace App\Repositories\Manage;

use App\Models\Wemch;
use Exception;

class WemchRepository
{

    public function getList($filter = [], $pageNum = 2, $pageSize = 10): array
    {
        $res = Wemch::from("wemch as s")
            ->join("supplier as ss", "ss.id", "=", "s.shop_id")
            ->when(!empty($filter['shop_title']), function ($query) use ($filter) {
                return $query->where("s.title", "like", "%{$filter['shop_title']}%");
            })
            ->when(!empty($filter['shop_id']), function ($query) use ($filter) {
                return $query->where("s.shop_id", intval($filter['shop_id']));
            })
            ->orderBy("s.id", "desc")
            ->paginate($pageSize, ["s.*", "ss.title as shop_title"], null, $pageNum)
            ->toArray();

        return filterPaginateData($res);
    }

    public function getOne($id = null)
    {
        return Wemch::query()->where("id", $id)->first();
    }

    public function getByShopId($id = null)
    {
        if (!$id)
            return null;

        return Wemch::query()->where("shop_id", $id)->orderBy("id", "desc")->first();
    }

    /**
     * @throws Exception
     */
    public function saveOrUpdate($data = [], $id = 0)
    {
        if (empty($data['shop_id']))
            throw new Exception("所属店铺必填");

        if (empty($data['mch_id']))
            throw new Exception("商户号必填");

        if (empty($data['secret']))
            throw new Exception("商户秘钥必填");

        if (empty($data['cert_path']))
            throw new Exception("证书路径必填");

        if (empty($data['key_path']))
            throw new Exception("私钥路径必填");

        if (!empty($data['id']))
            unset($data['id']);

        if (intval($id)) {
            Wemch::where("id", $id)->update($data);
            return $id;
        } else {
            return Wemch::create($data)->id;
        }
    }

    /**
     * 删除
     * @param null $id
     */
    public function del($id = null)
    {
        if (!intval($id))
            return retFail("参数错误");

        Wemch::query()->where(['id' => intval($id)])->delete();

        return retSuc([], "删除成功");
    }


}
